package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.BaseEnum;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.*;
import aiku.numericalcontroloa.Mapper.MasterControl.MessageNotificationMapper;
import aiku.numericalcontroloa.Model.Dto.ProductsDto;
import aiku.numericalcontroloa.Model.Dto.PurchaseOrdersDto;
import aiku.numericalcontroloa.Model.Dto.PurchasePartDto;
import aiku.numericalcontroloa.Model.Entity.*;
import aiku.numericalcontroloa.Model.Entity.MasterControl.MessageNotification;
import aiku.numericalcontroloa.Model.Vo.PurchaseInfoVo;
import aiku.numericalcontroloa.Model.Vo.PurchaseOrdersVo;
import aiku.numericalcontroloa.Model.Vo.PurchasePageInfoVo;
import aiku.numericalcontroloa.Service.ProductsService;
import aiku.numericalcontroloa.common.utils.DateUtils;
import aiku.numericalcontroloa.enums.RoleEnum;
import aiku.numericalcontroloa.project.system.pojo.entity.SysRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.ObjectUtils.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 马
 * @description 针对表【products】的数据库操作Service实现
 * @createDate 2024-02-23 11:02:39
 */
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products>
        implements ProductsService {
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private PaymentBillingMapper billsMapper;
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private PurchaseReceiptsMapper purchaseReceiptsMapper;
    @Autowired
    private SuppliersMapper suppliersMapper;
    @Autowired
    private ExamineMapper examineMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RemarksMapper remarksMapper;
    @Autowired
    private PurchasePartMapper purchasePartMapper;
    @Autowired
    private DevicesMapper devicesMapper;
    @Autowired
    private MessageNotificationMapper msgNotificationMapper;

    // @Override
    // public Result apply(ProductsDto productsDto) {
    // String userid = StpUtil.getLoginId().toString();
    // //TODO 权限判断还未做
    // //判断是否为空
    // if (productsDto == null) {
    // return Result.error("参数不能为空");
    // }
    // //拿出供应商id
    // String suppliersId = productsDto.getSuppliersId();
    //
    // Products products = new Products();
    // BeanUtils.copyProperties(productsDto, products);
    // //新增产品
    // int i = productsMapper.insert(products);
    //
    // //是全款还是分期，如果是分期，需要添加分期
    // if (!products.getPaymentType().equals("0")) {
    // //TODO 添加分期
    // PaymentBilling bills = new PaymentBilling();
    // bills.setOrderId(products.getProductsId());
    // bills.setSumPeriods(Integer.valueOf(products.getPaymentType()));
    //
    // // 获取当前日期,在当前日期上加上指定的月数
    // Calendar calendar = Calendar.getInstance();
    // calendar.add(Calendar.MONTH, Integer.valueOf(products.getPaymentType()));
    // Date deadlineDate = calendar.getTime();
    // bills.setDeadlineTime(deadlineDate);
    // bills.setResiduePeriods(Integer.valueOf(products.getPaymentType()));
    // //总金额是单价乘以数量
    // BigDecimal sum = products.getPrice().multiply(new
    // BigDecimal(products.getNumber()));
    // bills.setTotalAmount(sum);
    // //每期金额是总金额除以期数，取两位小数
    // BigDecimal periodAmount = sum.divide(new
    // BigDecimal(products.getPaymentType()), 2, RoundingMode.HALF_UP);
    // bills.setPhaseAmount(periodAmount);
    // bills.setBillsStatus("0"); //0待付款，1已付款，2已逾期 (指的是每期的状态)
    // //TODO 每月1号修改所有账单还款状态，全部修改吃待付款
    // i += billsMapper.insert(bills);
    //
    // //添加收款记录
    // Payment payment = new Payment();
    // payment.setGoodName(products.getProductsName());
    // payment.setGoodModel(products.getModel());
    // payment.setGoodPrice(sum);
    // payment.setGoodNum(productsDto.getNumber());
    // payment.setType(productsDto.getPaymentType());
    // payment.setStorageTime(new Date());
    // payment.setPurchaserName(userid);
    // payment.setSupplierId(productsDto.getSuppliersId());
    // payment.setSupplierPrice(sum);
    // int is = paymentMapper.insert(payment);
    // }
    //
    // //添加采购订单
    // PurchaseOrders purchaseOrders = new PurchaseOrders();
    //
    // //这是分期付款,仓库类型(1月结供库,2现金库,3其他库,4生产用品库,5成品库)
    // if(!products.getPaymentType().equals("0")){
    // purchaseOrders.setWarehouseType("1");
    // }
    // if (products.getPaymentType().equals("0")){
    // purchaseOrders.setWarehouseType("1");
    // }
    // purchaseOrders.setSuppliersId(suppliersId);
    // purchaseOrders.setProductsId(products.getProductsId());
    // purchaseOrders.setOrderStatus("1"); //0已处理，1待处理等
    // purchaseOrders.setNumber(products.getNumber());
    // purchaseOrders.setPrice(products.getPrice());
    // purchaseOrders.setOrderTime(products.getStorageTime());
    // Examine examine = examineMapper.selectOne(new
    // LambdaQueryWrapper<Examine>().eq(Examine::getUserId, userid));
    // purchaseOrders.setUserId(userid);
    // purchaseOrders.setManagementId(examine.getManagementId());
    // i += purchaseOrdersMapper.insert(purchaseOrders);
    //
    // //其他属性暂未添加
    // return i >=2 ? Result.success("申请成功") : Result.error("申请失败");
    // }

    /**
     * 员工查看采购订单列表，分页
     * 
     * @return
     * @param page
     * @param size
     */
    @Override
    public Result purchaseList(Integer page, Integer size) {
        Page<PurchaseOrders> pages = new Page<>(page, size);
        String userid = StpUtil.getLoginId().toString();

        // TODO 已做权限
        SysRole adminInfo = userService.isAdminInfo(userid);
        Integer rol = adminInfo.getId();
        LambdaQueryWrapper<PurchaseOrders> queryWrapper = new LambdaQueryWrapper<>();
        if (rol == RoleEnum.ROLE_4.getCode()) {// 业务员
            queryWrapper.eq(PurchaseOrders::getUserId, userid);
        } else if (rol == RoleEnum.ROLE_5.getCode()) {// 厂长
            queryWrapper.eq(PurchaseOrders::getManagementId, userid);
        } else if (rol == RoleEnum.ROLE_1.getCode()) {// 超级管理

        } else {
            return Result.error(201, "权限不足");
        }
        // 查询采购订单记录
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectPage(pages, queryWrapper).getRecords();
        // 查询有几条订单信息
        Long count = purchaseOrdersMapper.selectCount(queryWrapper);
        if (purchaseOrdersList == null || purchaseOrdersList.size() <= 0) {
            return Result.success(new PurchaseInfoVo());
        }
        // 查询供应商信息,拿到供应商名称
        List<String> suppliersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getSuppliersId)
                .collect(Collectors.toList());
        List<Suppliers> suppliersList = suppliersMapper
                .selectList(new LambdaQueryWrapper<Suppliers>().in(Suppliers::getId, suppliersIdList));
        Map<String, Suppliers> suppliersMap = suppliersList.stream()
                .collect(Collectors.toMap(Suppliers::getId, Function.identity()));
        // 有数据，新建Map集合
        Map<Object, PurchaseInfoVo> mapOne = new HashMap<>();
        // 拿到采购产品id，查询采购订单信息
        List<String> productsIdList = purchaseOrdersList.stream().map(PurchaseOrders::getProductsId)
                .collect(Collectors.toList());

        // 查询的订单，并且拷贝属性
        List<Products> products = productsMapper
                .selectList(new LambdaQueryWrapper<Products>().in(Products::getProductsId, productsIdList));
        Map<String, Products> productsMap = products.stream()
                .collect(Collectors.toMap(Products::getProductsId, Function.identity()));

        for (PurchaseOrders orders : purchaseOrdersList) {
            PurchaseInfoVo purchaseInVo = new PurchaseInfoVo();
            Products product = productsMap.get(orders.getProductsId());
            if (product != null) {
                BeanUtils.copyProperties(product, purchaseInVo);
            }
            // 供应商id相同,就吧名称添加到vo里面
            Suppliers suppliers = suppliersMap.get(orders.getSuppliersId());
            if (suppliers != null) {
                purchaseInVo.setSuppliersName(suppliers.getSuppliersName());
            }
            BeanUtils.copyProperties(orders, purchaseInVo);
            mapOne.put(orders.getId(), purchaseInVo);
        }

        // 拿到采购订单id，查询采购入库的有无订单
        List<String> PurchaseOrdersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getId)
                .collect(Collectors.toList());
        List<PurchaseReceipts> purchaseReceiptsList = purchaseReceiptsMapper
                .selectList(new LambdaQueryWrapper<PurchaseReceipts>().in(PurchaseReceipts::getPurchaseOrdersId,
                        PurchaseOrdersIdList));
        // 如果有值，则进行进行添加到VO
        if (purchaseReceiptsList != null || purchaseReceiptsList.size() > 0) {
            for (PurchaseReceipts receipts : purchaseReceiptsList) {
                PurchaseInfoVo infoVo = mapOne.get(receipts.getPurchaseOrdersId());
                infoVo.setReceiptsStatus(receipts.getReceiptsStatus());
                infoVo.setReceiptsTime(receipts.getReceiptsTime());
            }
        }

        List<PurchaseInfoVo> purchaseInfoVoList = new ArrayList<>(mapOne.values());
        // 根据时间排序,时间越新，排序越靠前
        purchaseInfoVoList.sort((o1, o2) -> o2.getOrderTime().compareTo(o1.getOrderTime()));
        PurchasePageInfoVo purchasePageInfoVo = new PurchasePageInfoVo();
        purchasePageInfoVo.setPurchaseInfoVoList(purchaseInfoVoList);
        purchasePageInfoVo.setTotal(count);
        return Result.success(purchasePageInfoVo);
    }

    /**
     * 员工查看入库申请列表，分页
     * 
     * @return
     * @param page           分页
     * @param size
     * @param receiptsStatus 入库状态
     */
    @Override
    public Result purchaseReceiptsInfoList(Integer page, Integer size, String receiptsStatus) {
        // TODO 已做权限
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<PurchaseOrders> queryWrapperOne = new LambdaQueryWrapper<>();
        SysRole adminInfo = userService.isAdminInfo(userid);
        Integer id = adminInfo.getId();
        if (id == RoleEnum.ROLE_4.getCode()) {
            // 如果是库管的话,则直接查询业务员的入库信息
            queryWrapperOne.eq(PurchaseOrders::getUserId, userid);
        } else if (id == RoleEnum.ROLE_5.getCode()) {
            // 如果是厂长的话,则查询该厂长的入库信息
            queryWrapperOne.eq(PurchaseOrders::getManagementId, userid);
        } else if (id == RoleEnum.ROLE_1.getCode()) {
            // 管理员
        } else {
            return Result.error(201, "权限不足");
        }
        List<PurchaseOrders> ordersList = purchaseOrdersMapper.selectList(queryWrapperOne);
        List<String> orderIdList = ordersList.stream().map(PurchaseOrders::getId).collect(Collectors.toList());
        Page<PurchaseReceipts> pages = new Page<>(page, size);
        if (orderIdList.isEmpty()) {
            return Result.success(new PurchasePageInfoVo());
        }
        // 查询入库信息
        LambdaQueryWrapper<PurchaseReceipts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PurchaseReceipts::getPurchaseOrdersId, orderIdList);
        // 根据时间排序,时间越新，排序越靠前
        queryWrapper.orderByDesc(PurchaseReceipts::getReceiptsTime);

        if (receiptsStatus != null && !receiptsStatus.equals("-1")) {
            queryWrapper.eq(PurchaseReceipts::getReceiptsStatus, receiptsStatus);
        }
        List<PurchaseReceipts> purchaseReceiptsList = purchaseReceiptsMapper.selectPage(pages, queryWrapper)
                .getRecords();
        // 查询入库数量
        Long count = purchaseReceiptsMapper.selectCount(queryWrapper);
        // 通过入库信息拿出采购订单id，查询采购订单信息
        List<String> purchaseOrdersIdList = purchaseReceiptsList.stream().map(PurchaseReceipts::getPurchaseOrdersId)
                .collect(Collectors.toList());
        if (purchaseReceiptsList == null || purchaseReceiptsList.size() <= 0) {
            return Result.success(new PurchaseInfoVo());
        }
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper
                .selectList(new LambdaQueryWrapper<PurchaseOrders>().in(PurchaseOrders::getId, purchaseOrdersIdList));
        // 拿到采购产品id，查询采购产品id信息
        List<String> productsIdList = purchaseOrdersList.stream().map(PurchaseOrders::getProductsId)
                .collect(Collectors.toList());
        List<Products> products = productsMapper
                .selectList(new LambdaQueryWrapper<Products>().in(Products::getProductsId, productsIdList));
        // 通过供应商id,查询供应商信息
        List<String> suppliersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getSuppliersId)
                .collect(Collectors.toList());
        List<Suppliers> suppliers = suppliersMapper
                .selectList(new LambdaQueryWrapper<Suppliers>().in(Suppliers::getId, suppliersIdList));
        Map<String, Suppliers> suppliersMap = suppliers.stream()
                .collect(Collectors.toMap(Suppliers::getId, Function.identity()));

        // 将数据封装到VO中
        Map<Object, PurchaseInfoVo> mapOne = new HashMap<>();

        for (PurchaseReceipts receipts : purchaseReceiptsList) {
            PurchaseInfoVo purchaseInfoVo = new PurchaseInfoVo();
            for (PurchaseOrders purchaseOrders : purchaseOrdersList) {
                if (receipts.getPurchaseOrdersId().equals(purchaseOrders.getId())) {
                    BeanUtils.copyProperties(purchaseOrders, purchaseInfoVo);
                    Suppliers supOne = suppliersMap.get(purchaseOrders.getSuppliersId());
                    if (supOne != null) {
                        purchaseInfoVo.setSuppliersName(supOne.getSuppliersName());
                    }
                }
            }
            BeanUtils.copyProperties(receipts, purchaseInfoVo);
            for (Products product : products) {
                if (receipts.getProductsId().equals(product.getProductsId())) {
                    BeanUtils.copyProperties(product, purchaseInfoVo);
                    purchaseInfoVo.setPrice(receipts.getPrice());
                    purchaseInfoVo.setNumber(receipts.getNumber());
                }
            }
            mapOne.put(receipts.getId(), purchaseInfoVo);
        }

        List<PurchaseInfoVo> purchaseInfoVoList = new ArrayList<>(mapOne.values());
        // 根据时间排序
        // if (purchaseInfoVoList != null && !purchaseInfoVoList.isEmpty()) {
        // purchaseInfoVoList.sort((o1, o2) ->
        // o2.getReceiptsTime().compareTo(o1.getReceiptsTime()));
        // }
        PurchasePageInfoVo purchasePageInfoVo = new PurchasePageInfoVo();
        purchasePageInfoVo.setPurchaseInfoVoList(purchaseInfoVoList);
        purchasePageInfoVo.setTotal(count);
        return Result.success(purchasePageInfoVo);
    }

    /**
     * 员工通过模糊查询,查询采购订单信息
     * 产品名称,型号,采购人来查询
     * 
     * @param name
     * @return
     */
    @Override
    public Result purchaseReceiptsInfo(String name) {
        // TODO 已做权限
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<PurchaseOrders> queryWrapperOne = new LambdaQueryWrapper<>();
        SysRole adminInfo = userService.isAdminInfo(userid);
        Integer id = adminInfo.getId();
        if (id == RoleEnum.ROLE_4.getCode()) {
            // 如果是库管
            queryWrapperOne.eq(PurchaseOrders::getUserId, userid);
        } else if (id == RoleEnum.ROLE_5.getCode()) {
            // 如果是厂长的话,则查询该厂长的入库信息
            queryWrapperOne.eq(PurchaseOrders::getManagementId, userid);
        } else if (id == RoleEnum.ROLE_1.getCode()) {
            // 管理员
        } else {
            return Result.error(201, "权限不足");
        }
        // 查询产品记录
        LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Products::getProductsName, name).or().like(Products::getModel, name).or()
                .like(Products::getPurchaser, name);
        List<Products> productsList = productsMapper.selectList(queryWrapper);
        List<String> productsIdList = productsList.stream().map(Products::getProductsId).collect(Collectors.toList());

        if (productsIdList.size() <= 0) {
            return Result.success(new PurchaseInfoVo());
        }
        // 查询订单采购信息
        queryWrapperOne.in(PurchaseOrders::getProductsId, productsIdList);
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(queryWrapperOne);
        List<String> suppliersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getSuppliersId)
                .collect(Collectors.toList());
        if (suppliersIdList.isEmpty()) {
            return Result.success(new PurchaseInfoVo());
        }
        // 查询供应商信息,拿到供应商名称
        List<Suppliers> suppliersList = suppliersMapper
                .selectList(new LambdaQueryWrapper<Suppliers>().in(Suppliers::getId, suppliersIdList));
        Map<String, Suppliers> suppliersMap = suppliersList.stream()
                .collect(Collectors.toMap(Suppliers::getId, Function.identity()));
        // 有数据，新建Map集合
        List<PurchaseInfoVo> arrayList = new ArrayList<>();

        for (PurchaseOrders purchaseOrders : purchaseOrdersList) {
            PurchaseInfoVo purchaseInfoVo = new PurchaseInfoVo();
            Suppliers supOne = suppliersMap.get(purchaseOrders.getSuppliersId());
            if (supOne != null) {
                purchaseInfoVo.setSuppliersName(supOne.getSuppliersName());
            }
            BeanUtils.copyProperties(purchaseOrders, purchaseInfoVo);
            for (Products product : productsList) {
                if (purchaseOrders.getProductsId().equals(product.getProductsId())) {
                    BeanUtils.copyProperties(product, purchaseInfoVo);
                }
            }
            arrayList.add(purchaseInfoVo);
        }
        PurchasePageInfoVo purchasePageInfoVo = new PurchasePageInfoVo();
        purchasePageInfoVo.setPurchaseInfoVoList(arrayList);
        purchasePageInfoVo.setTotal(Long.valueOf(arrayList.size()));
        return Result.success(purchasePageInfoVo);
    }

    /**
     * 员工通过模糊查询,查询入库单信息
     * 产品名称,型号,采购人来查询
     * 
     * @param name
     * @return
     */
    @Override
    public Result purchaseReceiptsInfos(String name) {
        // TODO 还未做权限
        // 先查询产品信息
        String userid = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<PurchaseOrders> queryWrapperOne = new LambdaQueryWrapper<>();
        SysRole adminInfo = userService.isAdminInfo(userid);
        Integer id = adminInfo.getId();
        if (id == RoleEnum.ROLE_4.getCode()) {
            // 如果是库管的话,则直接查询库管的入库信息
            queryWrapperOne.eq(PurchaseOrders::getUserId, userid);
        } else if (id == RoleEnum.ROLE_5.getCode()) {
            // 如果是厂长的话,则查询该厂长的入库信息
            queryWrapperOne.eq(PurchaseOrders::getManagementId, userid);
        } else if (id == RoleEnum.ROLE_1.getCode()) {
            // 管理员
        } else {
            return Result.error(201, "权限不足");
        }

        LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Products::getProductsName, name).or().like(Products::getModel, name).or()
                .like(Products::getPurchaser, name);
        List<Products> productsList = productsMapper.selectList(queryWrapper);
        if (productsList.size() <= 0) {
            return Result.success(new PurchaseInfoVo());
        }
        // 产品id
        List<String> productsIdList = productsList.stream().map(Products::getProductsId).collect(Collectors.toList());
        Map<String, Products> productsMap = productsList.stream()
                .collect(Collectors.toMap(Products::getProductsId, Function.identity()));
        // 根据产品id查询采购订单信息
        queryWrapperOne.in(PurchaseOrders::getProductsId, productsIdList);
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(queryWrapperOne);
        if (purchaseOrdersList.isEmpty()) {
            return Result.success(new PurchaseInfoVo());
        }
        List<String> suppliersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getSuppliersId)
                .collect(Collectors.toList());
        Map<String, PurchaseOrders> purchaseOrdersMap = purchaseOrdersList.stream()
                .collect(Collectors.toMap(PurchaseOrders::getId, Function.identity()));

        // 根据供应商id查询供应商信息
        List<Suppliers> suppliersList = suppliersMapper
                .selectList(new LambdaQueryWrapper<Suppliers>().in(Suppliers::getId, suppliersIdList));
        Map<String, Suppliers> suppliersMap = suppliersList.stream()
                .collect(Collectors.toMap(Suppliers::getId, Function.identity()));
        List<String> purchaseOrderIdList = purchaseOrdersList.stream().map(PurchaseOrders::getId)
                .collect(Collectors.toList());
        // 通过采购单id查询入库单信息
        List<PurchaseReceipts> purchaseReceiptsList = purchaseReceiptsMapper
                .selectList(new LambdaQueryWrapper<PurchaseReceipts>().in(PurchaseReceipts::getPurchaseOrdersId,
                        purchaseOrderIdList));

        List<PurchaseInfoVo> purchaseInfoVoList = new ArrayList<>();
        for (PurchaseReceipts purchaseReceipts : purchaseReceiptsList) {
            PurchaseOrders purchaseOrders = purchaseOrdersMap.get(purchaseReceipts.getPurchaseOrdersId());
            if (purchaseOrders == null) {
                continue;
            }
            Products products = productsMap.get(purchaseOrders.getProductsId());
            if (products == null) {
                continue;
            }
            Suppliers suppliers = suppliersMap.get(purchaseOrders.getSuppliersId());
            PurchaseInfoVo purchaseInfoVo = new PurchaseInfoVo();
            // Bean拷贝
            BeanUtils.copyProperties(purchaseOrders, purchaseInfoVo);
            BeanUtils.copyProperties(products, purchaseInfoVo);
            BeanUtils.copyProperties(suppliers, purchaseInfoVo);
            purchaseInfoVo.setReceiptsId(purchaseReceipts.getId());
            purchaseInfoVo.setReceiptsStatus(purchaseReceipts.getReceiptsStatus());
            purchaseInfoVoList.add(purchaseInfoVo);
        }

        return Result.success(purchaseInfoVoList);
    }

    /**
     * 管理修改入库单信息
     * 
     * @param purchaseInfoVo
     * @return
     */
    @Override
    public Result updateReceiptsInfo(PurchaseInfoVo purchaseInfoVo) {
        // TODO 还未检测管理权限
        // 查询入库订单信息
        PurchaseReceipts purchaseReceipts = purchaseReceiptsMapper.selectById(purchaseInfoVo.getReceiptsId());
        if (purchaseReceipts == null) {
            return Result.error("产品不存在");
        }
        BeanUtils.copyProperties(purchaseInfoVo, purchaseReceipts);
        // 更新入库单信息
        int i = purchaseReceiptsMapper.updateById(purchaseReceipts);
        return i > 0 ? Result.success("保存成功") : Result.error(201, "保存失败");
    }

    @Override
    public Result getPurchaseOrdersList(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null ||
                (purchaseOrdersDto.getCurrentPage() == null || purchaseOrdersDto.getPageSize() == null)) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Page<PurchaseOrders> ordersPage = new Page<>(purchaseOrdersDto.getCurrentPage(),
                purchaseOrdersDto.getPageSize());
        // 条件查询
        LambdaQueryWrapper<PurchaseOrders> purchaseOrdersLQW = new LambdaQueryWrapper<>();
        purchaseOrdersLQW.orderByDesc(PurchaseOrders::getCreateTime);
        // 按供应商id查询
        if (purchaseOrdersDto.getSuppliersId() != null && !purchaseOrdersDto.getSuppliersId().isEmpty()) {
            purchaseOrdersLQW.eq(PurchaseOrders::getSuppliersId, purchaseOrdersDto.getSuppliersId());
        }
        // 按采购人id查询
        if (purchaseOrdersDto.getUserId() != null && !purchaseOrdersDto.getUserId().isEmpty()) {
            purchaseOrdersLQW.eq(PurchaseOrders::getUserId, purchaseOrdersDto.getUserId());
        }
        // 根据结款方式查询
        if (purchaseOrdersDto.getPaymentMethod() != null) {
            purchaseOrdersLQW.eq(PurchaseOrders::getPaymentMethod, purchaseOrdersDto.getPaymentMethod());
        }
        // 根据订单状态查询
        if (purchaseOrdersDto.getOrderStatus() != null && !purchaseOrdersDto.getOrderStatus().isEmpty()) {
            purchaseOrdersLQW.eq(PurchaseOrders::getOrderStatus, purchaseOrdersDto.getOrderStatus());
        }

        // List<PurchaseOrders> purchaseOrdersList =
        // purchaseOrdersMapper.selectPage(ordersPage, purchaseOrdersLQW).getRecords();
        List<PurchaseOrders> purchaseOrdersList = purchaseOrdersMapper.selectList(purchaseOrdersLQW);

        if (purchaseOrdersList.isEmpty()) {
            List<PurchaseOrdersVo> ordersVoList = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("total", 0);
            map.put("ordersVoList", ordersVoList);
            return Result.success(map);
        }

        Map<String, Object> keyMap = getKeyMap(purchaseOrdersList);
        @SuppressWarnings("unchecked")
        Map<String, Suppliers> suppliersMap = (Map<String, Suppliers>) keyMap.get("suppliersMap");
        @SuppressWarnings("unchecked")
        Map<String, User> userMap = (Map<String, User>) keyMap.get("userMap");
        @SuppressWarnings("unchecked")
        Map<String, List<PurchasePartDto>> purchasePartMap = (Map<String, List<PurchasePartDto>>) keyMap
                .get("purchasePartMap");
        @SuppressWarnings("unchecked")
        Map<String, Remarks> remarksMap = (Map<String, Remarks>) keyMap.get("remarksMap");
        @SuppressWarnings("unchecked")
        Map<String, PurchaseReceipts> purchaseReceiptsMap = (Map<String, PurchaseReceipts>) keyMap
                .get("purchaseReceiptsMap");

        List<PurchaseOrdersVo> ordersVoList = new ArrayList<>();
        for (PurchaseOrders purchaseOrders : purchaseOrdersList) {
            PurchaseOrdersVo ordersVo = new PurchaseOrdersVo();
            BeanUtils.copyProperties(purchaseOrders, ordersVo);
            // 供应商名称
            ordersVo.setSuppliersName(suppliersMap.get(purchaseOrders.getSuppliersId()).getSuppliersName());
            // 采购人名称
            ordersVo.setUserName(userMap.get(purchaseOrders.getUserId()).getNickName());
            // 零件列表
            ordersVo.setParts(purchasePartMap.get(purchaseOrders.getId()));
            // 备注
            if (remarksMap.containsKey(purchaseOrders.getId())) {
                ordersVo.setRemark(remarksMap.get(purchaseOrders.getId()).getRemarkContent());
            }
            // 时间
            ordersVo.setCreateTime(DateUtils.YMDHMSFormat(purchaseOrders.getCreateTime()));
            // 入库状态
            if (purchaseReceiptsMap.containsKey(purchaseOrders.getId())) {
                ordersVo.setReceiptsStatus(purchaseReceiptsMap.get(purchaseOrders.getId()).getReceiptsStatus());
            }
            ordersVoList.add(ordersVo);
        }

        if (purchaseOrdersDto.getReceiptsStatus() != null && purchaseOrdersDto.getOrderStatus() != null
                && purchaseOrdersDto.getOrderStatus().equals("0") && purchaseOrdersDto.getReceiptsStatus() == 0) {
            ordersVoList = ordersVoList.stream()
                    .filter(item -> item.getReceiptsStatus() != null && item.getReceiptsStatus().equals("0"))
                    .collect(Collectors.toList());
        } else if (purchaseOrdersDto.getReceiptsStatus() != null && purchaseOrdersDto.getOrderStatus() != null
                && purchaseOrdersDto.getOrderStatus().equals("0") && purchaseOrdersDto.getReceiptsStatus() == 1) {
            ordersVoList = ordersVoList.stream().filter(item -> item.getReceiptsStatus() == null)
                    .collect(Collectors.toList());
        }
        int listLength = ordersVoList.size();
        int selectPageStart = (int) ((ordersPage.getCurrent() - 1) * ordersPage.getSize());
        int selectPageEnd = (int) (ordersPage.getCurrent() * ordersPage.getSize());
        if (selectPageEnd > listLength) {
            selectPageEnd = listLength;
        }
        ordersVoList = ordersVoList.subList(selectPageStart, selectPageEnd);

        Map<String, Object> map = new HashMap<>();
        // map.put("total", ordersPage.getTotal());
        map.put("total", listLength);
        map.put("ordersVoList", ordersVoList);
        return Result.success("查询成功", map);
    }

    @Override
    public Map<String, Object> getKeyMap(List<PurchaseOrders> purchaseOrdersList) {
        // 采购订单id列表
        List<String> purchaseOrdersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getId)
                .collect(Collectors.toList());
        // 供应商id列表
        Set<String> suppliersIdList = purchaseOrdersList.stream().map(PurchaseOrders::getSuppliersId)
                .collect(Collectors.toSet());
        // 采购人id列表
        Set<String> userIdList = purchaseOrdersList.stream().map(PurchaseOrders::getUserId).collect(Collectors.toSet());
        // 根据供应商id查询供应商
        List<Suppliers> suppliersList = suppliersMapper.selectBatchByIdWithDelete(suppliersIdList);
        // 使用流处理成Map集合，通过供应商id获取供应商对象
        Map<String, Suppliers> suppliersMap = suppliersList.stream()
                .collect(Collectors.toMap(Suppliers::getId, Function.identity()));

        // 根据采购订单id列表查询采购零件表
        LambdaQueryWrapper<PurchasePart> purchasePartLQW = new LambdaQueryWrapper<>();
        purchasePartLQW.in(PurchasePart::getPurchaseId, purchaseOrdersIdList);
        List<PurchasePart> purchasePartList = purchasePartMapper.selectList(purchasePartLQW);
        // 根据零件id查询产品表
        Set<String> devicesIdList = purchasePartList.stream().map(PurchasePart::getPartId).collect(Collectors.toSet());
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(devicesIdList);
        // 使用流处理成Map集合，方便通过零件id获取零件对象
        Map<String, Devices> devicesMap = devicesList.stream()
                .collect(Collectors.toMap(Devices::getId, Function.identity()));

        // 查用户
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        // 使用流处理成Map集合，方便通过用户id获取用户对象
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

        // 根据采购订单id列表查询备注
        LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
        remarksLQW.in(Remarks::getQueryId, purchaseOrdersIdList);
        List<Remarks> remarksList = remarksMapper.selectList(remarksLQW);
        // 使用流处理成Map集合，方便通过采购订单id获取备注对象
        Map<String, Remarks> remarksMap = remarksList.stream()
                .collect(Collectors.toMap(Remarks::getQueryId, remarks -> remarksList.stream()
                        .filter(item -> item.getQueryId().equals(remarks.getQueryId()))
                        .findFirst()
                        .orElse(null)));

        // 根据采购订单id查询入库列表
        LambdaQueryWrapper<PurchaseReceipts> purchaseReceiptsLQW = new LambdaQueryWrapper<>();
        purchaseReceiptsLQW.in(PurchaseReceipts::getPurchaseOrdersId, purchaseOrdersIdList);
        List<PurchaseReceipts> purchaseReceiptsList = purchaseReceiptsMapper.selectList(purchaseReceiptsLQW);
        // 通过采购订单id，获取入库对象
        Map<String, PurchaseReceipts> purchaseReceiptsMap = new HashMap<>();
        if (purchaseReceiptsList.size() > 0) {
            purchaseReceiptsMap = purchaseReceiptsList.stream()
                    .collect(Collectors.toMap(PurchaseReceipts::getPurchaseOrdersId, p -> purchaseReceiptsList.stream()
                            .filter(purchaseReceipts -> purchaseReceipts.getPurchaseOrdersId()
                                    .equals(p.getPurchaseOrdersId()))
                            .findFirst()
                            .orElse(null)));
        }

        // 处理数据
        // 先处理采购零件
        // 通过采购订单id，获取采购产品列表
        Map<String, List<PurchasePartDto>> purchasePartMap = new HashMap<>();
        for (PurchasePart purchasePart : purchasePartList) {
            Devices devices = devicesMap.get(purchasePart.getPartId());
            PurchasePartDto purchasePartDto = new PurchasePartDto();
            BeanUtils.copyProperties(purchasePart, purchasePartDto);
            // 零件名
            purchasePartDto.setPartName(devices.getPartName());
            // 零件型号
            purchasePartDto.setModel(devices.getModel());
            // 零件图片
            purchasePartDto.setImage(devices.getImage());
            // 描述
            purchasePartDto.setDevicesDescribe(devices.getDevicesDescribe());
            // 备注
            purchasePartDto.setRemark(devices.getRemark());
            // 上次的采购单价
            if (purchasePart.getCost() == null) {
                purchasePartDto.setCost(devices.getCost());
            }

            if (!purchasePartMap.containsKey(purchasePart.getPurchaseId())) {
                // 没有采购订单id的key,新建零件集合
                List<PurchasePartDto> partDtoList = new ArrayList<>();
                partDtoList.add(purchasePartDto);
                purchasePartMap.put(purchasePart.getPurchaseId(), partDtoList);
            } else {
                purchasePartMap.get(purchasePart.getPurchaseId()).add(purchasePartDto);
            }
        }

        Map<String, Object> keyMap = new HashMap<>();
        keyMap.put("suppliersMap", suppliersMap);
        keyMap.put("userMap", userMap);
        keyMap.put("purchasePartMap", purchasePartMap);
        keyMap.put("remarksMap", remarksMap);
        keyMap.put("purchaseReceiptsMap", purchaseReceiptsMap);
        return keyMap;
    }

    @Override
    @Transactional
    public Result addPurchaseOrders(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        PurchaseOrders purchaseOrders = new PurchaseOrders();
        if (purchaseOrdersDto.getSuppliersId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 设置供应商
        purchaseOrders.setSuppliersId(purchaseOrdersDto.getSuppliersId());
        boolean root = user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString()) ||
                user.getRoleId().equals(RoleEnum.ROLE_4.getCodeToString());
        // 权限为管理员
        // 设置采购人
        if (root && purchaseOrdersDto.getUserId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        } else if (root && purchaseOrdersDto.getUserId() != null) {
            purchaseOrders.setUserId(purchaseOrdersDto.getUserId());
        } else {
            purchaseOrders.setUserId(user.getId());
        }
        // 设置总金额
        if (purchaseOrdersDto.getPrice() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        purchaseOrders.setPrice(purchaseOrdersDto.getPrice());
        // 设置结款方式
        if (purchaseOrdersDto.getPaymentMethod() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        purchaseOrders.setPaymentMethod(purchaseOrdersDto.getPaymentMethod());
        // 设置订单状态为待审核
        purchaseOrders.setOrderStatus("1");
        // 插入数据
        purchaseOrdersMapper.insert(purchaseOrders);

        // 设置零件列表
        if (purchaseOrdersDto.getParts() == null && purchaseOrdersDto.getParts().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        for (PurchasePart purchasePart : purchaseOrdersDto.getParts()) {
            purchasePart.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            purchasePart.setPurchaseId(purchaseOrders.getId());
            purchasePart.setCreateTime(new Date());
            purchasePart.setUpdateTime(new Date());
        }
        if (!purchaseOrdersDto.getParts().isEmpty()) {
            purchasePartMapper.insertBatch(purchaseOrdersDto.getParts());
        }

        // 设置备注
        if (purchaseOrdersDto.getRemark() != null) {
            Remarks remarks = new Remarks();
            remarks.setQueryId(purchaseOrders.getId());
            remarks.setRemarkContent(purchaseOrdersDto.getRemark());
            remarksMapper.insert(remarks);
        }

        // 创建消息通知
        // 查厂长角色、管理员角色
        List<String> roleIdList = new ArrayList<>();
        roleIdList.add(RoleEnum.ROLE_1.getCodeToString());
        roleIdList.add(RoleEnum.ROLE_5.getCodeToString());
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt())
                .in(User::getRoleId, roleIdList);
        List<User> userList = userMapper.selectList(userLQW);
        if (!userList.isEmpty()) {
            List<MessageNotification> msgList = new ArrayList<>();
            for (User admin : userList) {
                MessageNotification msg = new MessageNotification();
                msg.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                // 标题
                msg.setTitle("有新的采购申请待审核");
                // 内容
                User user1 = userMapper.selectById(purchaseOrders.getUserId());
                String content = user1.getNickName() + "申请采购（采购总金额：" + purchaseOrders.getPrice() + "元）";
                msg.setContent(content);
                // 发布人为采购人
                msg.setPublisherId(user1.getId());
                // 接收人为厂长，管理员
                msg.setReceiverId(admin.getId());
                // 关联id
                msg.setRelevanceId(purchaseOrders.getId());
                // 类型为仓库管理
                msg.setMsgType(6);
                // 子菜单为1采购管理
                msg.setSubmenu(1);
                // 状态为待处理
                msg.setStatus(0);
                msg.setCreateTime(new Date());
                msgList.add(msg);
            }
            msgNotificationMapper.insertBatch(msgList);
        }
        return Result.success("添加成功");
    }

    @Override
    public Result getPurchaseOrders(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null || purchaseOrdersDto.getId() == null || purchaseOrdersDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        PurchaseOrders purchaseOrders = purchaseOrdersMapper.selectById(purchaseOrdersDto.getId());
        if (purchaseOrders == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        PurchaseOrdersVo purchaseOrdersVo = new PurchaseOrdersVo();
        BeanUtils.copyProperties(purchaseOrders, purchaseOrdersVo);
        // 供应商名称
        Suppliers suppliers = suppliersMapper.selectByIdWithDelete(purchaseOrders.getSuppliersId());
        purchaseOrdersVo.setSuppliersName(suppliers.getSuppliersName());
        // 采购人名称
        User user = userMapper.selectById(purchaseOrders.getUserId());
        purchaseOrdersVo.setUserName(user.getNickName());
        // 零件列表
        LambdaQueryWrapper<PurchasePart> purchasePartLQW = new LambdaQueryWrapper<>();
        purchasePartLQW.eq(PurchasePart::getPurchaseId, purchaseOrders.getId());
        List<PurchasePart> purchasePartList = purchasePartMapper.selectList(purchasePartLQW);
        // 获取设备列表
        Set<String> partIdList = purchasePartList.stream().map(PurchasePart::getPartId).collect(Collectors.toSet());
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(partIdList);
        // 处理成map
        Map<String, Devices> devicesMap = devicesList.stream()
                .collect(Collectors.toMap(Devices::getId, devices -> devicesList.stream()
                        .filter(item -> item.getId().equals(devices.getId()))
                        .findFirst()
                        .orElse(null)));
        List<PurchasePartDto> partDtoList = new ArrayList<>();
        for (PurchasePart purchasePart : purchasePartList) {
            PurchasePartDto purchasePartDto = new PurchasePartDto();
            BeanUtils.copyProperties(purchasePart, purchasePartDto);
            purchasePartDto.setPartName(devicesMap.get(purchasePart.getPartId()).getPartName());
            purchasePartDto.setModel(devicesMap.get(purchasePart.getPartId()).getModel());
            purchasePartDto.setImage(devicesMap.get(purchasePart.getPartId()).getImage());
            partDtoList.add(purchasePartDto);
        }
        purchaseOrdersVo.setParts(partDtoList);
        // 备注
        LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
        remarksLQW.eq(Remarks::getQueryId, purchaseOrders.getId());
        Remarks remarks = remarksMapper.selectOne(remarksLQW);
        if (remarks != null) {
            purchaseOrdersVo.setRemark(remarks.getRemarkContent());
        }
        return Result.success("查询成功", purchaseOrdersVo);
    }

    @Override
    public Result updatePurchaseOrders(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null || purchaseOrdersDto.getId() == null || purchaseOrdersDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该采购订单
        PurchaseOrders purchaseOrders = purchaseOrdersMapper.selectById(purchaseOrdersDto.getId());
        if (purchaseOrders == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        // 修改供应商
        if (purchaseOrdersDto.getSuppliersId() != null) {
            purchaseOrders.setSuppliersId(purchaseOrdersDto.getSuppliersId());
        }
        // 修改采购人
        if (purchaseOrdersDto.getUserId() != null) {
            purchaseOrders.setUserId(purchaseOrdersDto.getUserId());
        }
        // 修改结款方式
        if (purchaseOrdersDto.getPaymentMethod() != null) {
            purchaseOrders.setPaymentMethod(purchaseOrdersDto.getPaymentMethod());
        }
        // 修改总金额
        if (purchaseOrdersDto.getPrice() != null) {
            purchaseOrders.setPrice(purchaseOrdersDto.getPrice());
        }
        // 修改零件列表，将原来的零件列表删除，新增
        if (purchaseOrdersDto.getParts().size() > 0) {
            // 删除原来的列表
            purchasePartMapper.deletedByPurchaseId(purchaseOrders.getId());
            // 新增
            for (PurchasePart purchasePart : purchaseOrdersDto.getParts()) {
                purchasePart.setId(null);
                purchasePart.setPurchaseId(purchaseOrders.getId());
                purchasePartMapper.insert(purchasePart);
            }
        }
        // 更新为待审核
        purchaseOrders.setOrderStatus("1");
        // 更新采购订单
        purchaseOrdersMapper.updateById(purchaseOrders);

        // 修改备注
        if (purchaseOrdersDto.getRemark() != null) {
            // 查询是否有备注
            LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
            remarksLQW.eq(Remarks::getQueryId, purchaseOrders.getId());
            Remarks remarks = remarksMapper.selectOne(remarksLQW);
            if (remarks == null) {
                remarks = new Remarks();
                remarks.setQueryId(purchaseOrders.getId());
                remarks.setRemarkContent(purchaseOrdersDto.getRemark());
                remarksMapper.insert(remarks);
            }else {
                remarks.setRemarkContent(purchaseOrdersDto.getRemark());
                remarksMapper.updateById(remarks);
            }
        }
        return Result.success("修改成功");
    }

    @Override
    public Result applyPurchaseOrders(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(purchaseOrdersDto is null)");
        }
        if (purchaseOrdersDto.getId() == null || purchaseOrdersDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "参数为空(purchaseOrdersDto[id] is null)");
        }
        // 厂长、管理员有权
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString()) &&
                !user.getRoleId().equals(RoleEnum.ROLE_5.getCodeToString())) {
            return new Result(HttpStatus.FORBIDDEN, "无权访问");
        }
        // 查询是否有该订单
        PurchaseOrders purchaseOrders = purchaseOrdersMapper.selectById(purchaseOrdersDto.getId());
        if (purchaseOrders == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        // 修改订单状态
        purchaseOrders.setOrderStatus(purchaseOrdersDto.getOrderStatus());
        LambdaUpdateWrapper<PurchaseOrders> purchaseOrdersLUW = new LambdaUpdateWrapper<>();
        purchaseOrdersLUW.eq(PurchaseOrders::getId, purchaseOrders.getId())
                .set(PurchaseOrders::getOrderStatus, purchaseOrders.getOrderStatus());
        purchaseOrdersMapper.update(null, purchaseOrdersLUW);
        // 创建消息通知
        String status;
        if (purchaseOrders.getOrderStatus().equals("0")) {
            status = "已通过";
        } else {
            status = "未通过";
        }
        MessageNotification msg = new MessageNotification();
        // 标题
        String title = "采购申请" + status;
        msg.setTitle(title);
        // 内容
        String content = "您采购总金额为" + purchaseOrders.getPrice() + "元的采购申请" + status;
        msg.setContent(content);
        // 发布人为审核人
        msg.setPublisherId(user.getId());
        // 接收人为采购人
        msg.setReceiverId(purchaseOrders.getUserId());
        // 关联id
        msg.setRelevanceId(purchaseOrders.getId());
        // 类型为仓库管理
        msg.setMsgType(6);
        // 子菜单为7采购详情
        msg.setSubmenu(7);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("操作成功");
    }

    @Override
    public Result oneKeyPurchaseOrders(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null || purchaseOrdersDto.getId() == null || purchaseOrdersDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该订单
        PurchaseOrders purchaseOrders = purchaseOrdersMapper.selectById(purchaseOrdersDto.getId());
        if (purchaseOrders == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        // 查询是否有该订单入库记录
        LambdaQueryWrapper<PurchaseReceipts> purchaseReceiptsLQW = new LambdaQueryWrapper<>();
        purchaseReceiptsLQW.eq(PurchaseReceipts::getPurchaseOrdersId, purchaseOrders.getId());
        PurchaseReceipts purchaseReceipts = purchaseReceiptsMapper.selectOne(purchaseReceiptsLQW);
        if (purchaseReceipts == null) {
            // 创建入库记录
            purchaseReceipts = new PurchaseReceipts();
            // 采购订单id
            purchaseReceipts.setPurchaseOrdersId(purchaseOrders.getId());
            // 入库时间
            purchaseReceipts.setReceiptsTime(new Date());
            // 入库申请人
            purchaseReceipts.setUserId(StpUtil.getLoginIdAsString());
            // 入库状态，待审核
            purchaseReceipts.setReceiptsStatus("1");
            // 插入新数据
            purchaseReceiptsMapper.insert(purchaseReceipts);
        } else {
            // 修改入库状态
            // 入库时间
            purchaseReceipts.setReceiptsTime(new Date());
            // 入库申请人
            purchaseReceipts.setUserId(StpUtil.getLoginIdAsString());
            // 入库状态，待审核
            purchaseReceipts.setReceiptsStatus("1");
            LambdaUpdateWrapper<PurchaseReceipts> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(PurchaseReceipts::getId, purchaseReceipts.getId())
                    .set(PurchaseReceipts::getReceiptsTime, purchaseReceipts.getReceiptsTime())
                    .set(PurchaseReceipts::getUserId, purchaseReceipts.getUserId())
                    .set(PurchaseReceipts::getReceiptsStatus, purchaseReceipts.getReceiptsStatus());
            purchaseReceiptsMapper.update(null, lambdaUpdateWrapper);
        }
        // 创建消息通知
        // 查厂长角色、管理员角色
        List<String> roleIdList = new ArrayList<>();
        roleIdList.add(RoleEnum.ROLE_1.getCodeToString());
        roleIdList.add(RoleEnum.ROLE_5.getCodeToString());
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt())
                .in(User::getRoleId, roleIdList);
        List<User> userList = userMapper.selectList(userLQW);
        if (!userList.isEmpty()) {
            List<MessageNotification> msgList = new ArrayList<>();
            for (User admin : userList) {
                MessageNotification msg = new MessageNotification();
                msg.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                // 标题
                msg.setTitle("有新的一键入库申请待审批");
                // 内容
                User user1 = userMapper.selectById(purchaseReceipts.getUserId());
                String content = user1.getNickName() + "申请入库";
                msg.setContent(content);
                // 发布人为申请人
                msg.setPublisherId(user1.getId());
                // 接收人为厂长，管理员
                msg.setReceiverId(admin.getId());
                // 关联id
                msg.setRelevanceId(purchaseReceipts.getId());
                // 类型为仓库管理
                msg.setMsgType(6);
                // 子菜单为2入库管理
                msg.setSubmenu(2);
                // 状态为待处理
                msg.setStatus(0);
                msg.setCreateTime(new Date());
                msgList.add(msg);
            }
            msgNotificationMapper.insertBatch(msgList);
        }
        return Result.success("操作成功");
    }

    @Override
    public Result deletePurchasing(PurchaseOrdersDto purchaseOrdersDto) {
        if (purchaseOrdersDto == null ||
                (purchaseOrdersDto.getId() == null || purchaseOrdersDto.getId().isEmpty())) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        purchaseOrdersMapper.deleteById(purchaseOrdersDto.getId());
        return Result.success("删除成功");
    }
}
